﻿using Hidistro.Core;
using Hidistro.Entities.Orders;
using Hidistro.Entities.Sales;
using Hidistro.SaleSystem.Shopping;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hidistro.Membership.Core;
using Hidistro.Membership.Context;
using wnxd.javascript;
using Hidistro.Messages;

namespace JuseWeb.Vshop
{
    public partial class SpreadShoppingCart : System.Web.UI.Page
    {
        Database database = DatabaseFactory.CreateDatabase();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Request.UserAgent.IndexOf("MicroMessenger") == -1 || string.IsNullOrEmpty(this.Request["Sku"])) this.Response.Redirect("Default.aspx");
            List<PInfo> info = this.GetInfo(this.Request["Sku"]);
            if (info.Count == 0) this.Response.Redirect("Default.aspx");
            this.pImage.Src = info[0].Image;
            this.pName.InnerText = info[0].ProductName;
            this.pPrice.InnerText = Globals.FormatMoney(info[0].SalePrice);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < info.Count; i++)
            {
                string first = "";
                if (i == 0)
                {
                    first = " wnxd_active";
                }
                sb.AppendFormat("<li skuid=\"{0}\" name=\"{5}\" price=\"{1}\" stock=\"{2}\" image=\"{6}\"><a class=\"wnxd_a{3}\" href=\"javascript:void(0);\">{4}</a></li>", info[i].SkuId, Globals.FormatMoney(info[i].SalePrice), info[i].Stock, first, info[i].Name, info[i].ProductName, info[i].Image);
            }
            this.sku_ul.InnerHtml = sb.ToString();
        }
        private List<PInfo> GetInfo(string SkuId)
        {
            DbCommand cmd = database.GetSqlStringCommand(string.Format("select t1.*,t2.ThumbnailUrl100,t2.ProductName from ((SELECT s.SkuId, ValueStr, w.ProductId,w.Stock,w.SalePrice FROM Hishop_SKUItems s join Hishop_Attributes a on s.AttributeId = a.AttributeId join Hishop_AttributeValues av on s.ValueId = av.ValueId join Hishop_SKUs w on w.SkuId = s.SkuId and w.ProductId = {0}) UNION ALL (SELECT s.SkuId, ValueStr, w.ProductId,w.Stock,w.SalePrice FROM Hishop_SKUItems s join Hishop_Attributes a on s.AttributeId = a.AttributeId join Hishop_AttributeValues av on s.ValueId = av.ValueId join (select * from (select t2.* from (select ProductId from wnxd_ProductSimilar where SimilarId = (select SimilarId from wnxd_ProductSimilar where ProductId = {0}) and ProductId != {0}) t1 left join Hishop_SKUs t2 on t2.ProductId = t1.ProductId) t1 where SKU in (select min(t1.SKU) from (select t2.* from (select ProductId from wnxd_ProductSimilar where SimilarId = (select SimilarId from wnxd_ProductSimilar where ProductId = {0}) and ProductId != {0}) t1 left join Hishop_SKUs t2 on t2.ProductId = t1.ProductId) t1 group by t1.ProductId)) w on w.SkuId = s.SkuId)) t1 left join Hishop_Products t2 on t2.ProductId = t1.ProductId", SkuId == null ? "0" : SkuId));
            List<PInfo> list = new List<PInfo>();
            using (IDataReader reader = database.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    PInfo t = new PInfo();
                    t.Image = reader["ThumbnailUrl100"].ToString();
                    t.SkuId = reader["SkuId"].ToString();
                    t.Name = reader["ValueStr"].ToString();
                    t.ProductName = reader["ProductName"].ToString();
                    t.SalePrice = (decimal)reader["SalePrice"];
                    list.Add(t);
                }
            }
            return list;
        }
        protected string Submit(Page Page)
        {
            json json = new json(new { error = true });
            string skuid = Page.Request.Form["SkuId"], name = Page.Request.Form["name"], tel = Page.Request.Form["tel"], address = Page.Request.Form["address"];
            int region;
            if (string.IsNullOrEmpty(skuid))
            {
                json["msg"] = "请选择要购买的商品";
            }
            else if (string.IsNullOrEmpty(name))
            {
                json["msg"] = "请输入正确的收货人姓名";
            }
            else if (string.IsNullOrEmpty(tel))
            {
                json["msg"] = "请输入正确的手机号码";
            }
            else if (string.IsNullOrEmpty(address))
            {
                json["msg"] = "请输入收货人详细地址";
            }
            else if (!int.TryParse(Page.Request.Form["region"], out region) || region == 0)
            {
                json["msg"] = "请选择收货地址";
            }
            else
            {
                ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(skuid, 1, true);
                OrderInfo orderInfo = GetOrderInfo(shoppingCart);
                if (ShoppingProcessor.CreatOrder(orderInfo))
                {
                    Messenger.OrderCreated(orderInfo, HiContext.Current.User);
                    orderInfo.OnCreated();
                    json["error"] = false;
                    json["url"] = Globals.GetSiteUrls().UrlData.FormatUrl("FinishOrder", new object[] { orderInfo.OrderId });
                }
                else
                {
                    json["msg"] = "购买失败";
                }
            }
            return json.ToString();
        }
        private OrderInfo GetOrderInfo(ShoppingCartInfo shoppingCartInfo)
        {
            OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(shoppingCartInfo, false, false, true);
            if (orderInfo == null)
            {
                return null;
            }
            orderInfo.OrderId = this.GenerateOrderId();
            orderInfo.OrderDate = DateTime.Now;
            IUser user = HiContext.Current.User;
            orderInfo.UserId = user.UserId;
            orderInfo.Username = user.Username;
            orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
            orderInfo.RefundStatus = RefundStatus.None;
            FillOrderShippingMode(orderInfo, shoppingCartInfo);
            FillOrderPaymentMode(orderInfo);
            orderInfo.OrderSource = OrderSource.WeiXin;
            return orderInfo;
        }
        private string GenerateOrderId()
        {
            string str = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 7; i++)
            {
                int num = random.Next();
                str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
            }
            int v = random.Next(0, 9);
            return (DateTime.Now.ToString("yyyyMMdd") + str + v);
        }
        private void FillOrderShippingMode(OrderInfo orderInfo, ShoppingCartInfo shoppingCartInfo)
        {
            orderInfo.ShippingRegion = this.dropRegions.SelectedRegions;
            orderInfo.Address = Globals.HtmlEncode(Request.Form["address"]);
            orderInfo.ShipTo = Globals.HtmlEncode(Request.Form["name"]);
            orderInfo.CellPhone = Request.Form["tel"];
            orderInfo.ShippingModeId = int.Parse("2", System.Globalization.NumberStyles.None);
            orderInfo.RegionId = int.Parse(this.Request.Form["region"]);
            orderInfo.ShipToDate = "时间不限";
            ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(orderInfo.ShippingModeId, true);
            if (shippingMode != null)
            {
                orderInfo.ShippingModeId = shippingMode.ModeId;
                orderInfo.ModeName = shippingMode.Name;
                if (!(shoppingCartInfo.IsFreightFree || ((shoppingCartInfo.LineItems.Count<ShoppingCartItemInfo>(a => !a.IsfreeShipping) <= 0) && (shoppingCartInfo.LineGifts.Count <= 0))))
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, shoppingCartInfo.Weight, shippingMode);
                }
                else
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
                }
            }
        }
        private void FillOrderPaymentMode(OrderInfo orderInfo)
        {
            orderInfo.PaymentTypeId = 1;
            PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(orderInfo.PaymentTypeId);
            if (paymentMode != null)
            {
                orderInfo.PaymentType = Globals.HtmlEncode(paymentMode.Name);
                orderInfo.PayCharge = ShoppingProcessor.CalcPayCharge(orderInfo.GetTotal(), paymentMode);
                orderInfo.Gateway = paymentMode.Gateway;
            }
        }
        class PInfo
        {
            public string Image;
            public string SkuId;
            public string Name;
            public string ProductName;
            public decimal SalePrice;
            public int Stock;
        }
    }
}